package com.jiaomatech.doc.controller;

import com.jiaomatech.doc.dto.Doc;
import com.jiaomatech.doc.service.WordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class WordController {

    @Autowired
    private WordService wordService;

    @RequestMapping(value = "/word2", method = RequestMethod.GET)
    public String word2(ModelMap modelMap, @RequestParam String url) {
        Doc doc = wordService.table(url);
        modelMap.put("doc", doc);
        return "word2";
    }

    @RequestMapping(value = "/word3", method = RequestMethod.GET)
    public String word3(
        ModelMap modelMap,
        @RequestParam String url,
        @RequestParam(required = false) String exportWord
    ) {
        Doc doc = wordService.table(url);
        modelMap.put("doc", cleanDoc(doc));
        if (!StringUtils.isEmpty(exportWord)) {
            modelMap.put("exportWord", exportWord);
        }
        return "word3";
    }

    @RequestMapping(value = "/word4", method = RequestMethod.GET)
    public String word4(
        ModelMap modelMap,
        @RequestParam String url,
        @RequestParam(required = false) String exportWord
    ) {
        Doc doc = wordService.table(url);
        modelMap.put("doc", cleanDoc(doc));
        if (!StringUtils.isEmpty(exportWord)) {
            modelMap.put("exportWord", exportWord);
        }
        return "word4";
    }

    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public String excel(
        ModelMap modelMap,
        @RequestParam String url,
        @RequestParam(required = false) String exportWord
    ) {
        Doc doc = wordService.table(url);
        modelMap.put("doc", cleanDoc(doc));
        if (!StringUtils.isEmpty(exportWord)) {
            modelMap.put("exportWord", exportWord);
        }
        return "excel";
    }

    private Doc cleanDoc(Doc doc) {
        if (StringUtils.isBlank(doc.getBasePath())) {
            doc.setBasePath("");
        }
        doc.getTags().forEach(tag -> {
            tag.setName(cleanName(tag.getName()));
            tag.getApis().forEach(api -> {
                api.setTag(cleanName(api.getTag()));
                api.setDescription("");
            });
        });
        return doc;
    }

    private String cleanName(String name) {
        if (StringUtils.isEmpty(name)) {
            return "";
        }
        return name.split("-")[0];
    }
}
